package com.aura.springbook.controller;

import com.aura.springbook.common.R;
import com.aura.springbook.common.util.ResponseUtil;
import com.aura.springbook.model.User;
import com.aura.springbook.model.request.ChangePasswordRequest;
import com.aura.springbook.model.request.UserLoginRequest;
import com.aura.springbook.model.request.UserRegisterRequest;
import com.aura.springbook.model.request.UserUpdateRequest;
import com.aura.springbook.model.vo.UserVO;
import com.aura.springbook.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户接口", description = "用户相关操作接口")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户注册
     */
    @PostMapping
    @Operation(summary = "用户注册", description = "普通用户注册账户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "注册成功", 
            content = @Content(mediaType = "application/json", 
                schema = @Schema(implementation = R.class))),
        @ApiResponse(responseCode = "400", description = "用户已存在"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public R<Map<String, Object>> register(@RequestBody UserRegisterRequest registerRequest) {
        logger.info("收到用户注册请求, 用户名: {}", registerRequest.getUsername());
        
        User user = new User();
        BeanUtils.copyProperties(registerRequest, user);
        
        try {
            Long userId = userService.register(user);
            Map<String, Object> data = new HashMap<>();
            data.put("id", userId);
            logger.info("用户注册成功, 用户ID: {}", userId);
            return ResponseUtil.success(data);
        } catch (Exception e) {
            logger.error("用户注册失败, 用户名: {}, 错误信息: {}", registerRequest.getUsername(), e.getMessage(), e);
            return R.fail(com.aura.springbook.common.exception.ResultCode.USER_EXIST, e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录系统")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登录成功"),
        @ApiResponse(responseCode = "401", description = "登录失败")
    })
    public R<Map<String, Object>> login(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request) {
        logger.info("收到用户登录请求, 用户名: {}", loginRequest.getUsername());
        
        User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
        if (user != null) {
            // 将用户信息存储在session中
            HttpSession session = request.getSession();
            session.setAttribute("userId", user.getId());
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("realName", user.getRealName());
            data.put("phone", user.getPhone());
            data.put("role", user.getRole()); // 添加角色信息
            logger.info("用户登录成功, 用户ID: {}, 用户名: {}", user.getId(), user.getUsername());
            return ResponseUtil.success(data);
        } else {
            logger.warn("用户登录失败, 用户名: {}", loginRequest.getUsername());
            return ResponseUtil.fail(com.aura.springbook.common.exception.ResultCode.LOGIN_FAIL);
        }
    }
    
    /**
     * 查询个人信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询个人信息", description = "根据用户ID查询个人信息")
    @Parameter(name = "id", description = "用户ID", required = true)
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public R<UserVO> getUserInfo(@PathVariable Long id) {
        logger.info("收到查询用户信息请求, 用户ID: {}", id);
        
        User user = userService.getUserById(id);
        if (user != null) {
            UserVO userVO = UserVO.fromUser(user);
            logger.info("查询用户信息成功, 用户ID: {}", id);
            return ResponseUtil.success(userVO);
        } else {
            logger.warn("查询用户信息失败, 用户ID: {} 不存在", id);
            return ResponseUtil.notFound();
        }
    }
    
    /**
     * 修改个人信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "修改个人信息", description = "修改用户个人信息")
    @Parameters({
        @Parameter(name = "id", description = "用户ID", required = true),
        @Parameter(name = "updateRequest", description = "用户信息更新请求", required = true)
    })
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "修改成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public R<String> updateUserInfo(@PathVariable Long id, @RequestBody UserUpdateRequest updateRequest) {
        logger.info("收到修改用户信息请求, 用户ID: {}", id);
        
        User user = new User();
        BeanUtils.copyProperties(updateRequest, user);
        
        boolean result = userService.updateUserInfo(id, user);
        if (result) {
            logger.info("修改用户信息成功, 用户ID: {}", id);
            return ResponseUtil.success("修改成功");
        } else {
            logger.warn("修改用户信息失败, 用户ID: {} 不存在", id);
            return ResponseUtil.notFound();
        }
    }
    
    /**
     * 修改密码
     */
    @PutMapping("/{id}/password")
    @Operation(summary = "修改密码", description = "修改用户登录密码")
    @Parameters({
        @Parameter(name = "id", description = "用户ID", required = true),
        @Parameter(name = "changePasswordRequest", description = "密码修改请求", required = true)
    })
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "密码修改成功"),
        @ApiResponse(responseCode = "400", description = "新密码与旧密码相同")
    })
    public R<String> changePassword(@PathVariable Long id, @RequestBody ChangePasswordRequest changePasswordRequest) {
        logger.info("收到修改用户密码请求, 用户ID: {}", id);
        
        boolean result = userService.changePassword(id, changePasswordRequest.getNewPassword());
        if (result) {
            logger.info("修改用户密码成功, 用户ID: {}", id);
            return ResponseUtil.success("密码修改成功");
        } else {
            logger.warn("修改用户密码失败, 用户ID: {}", id);
            return ResponseUtil.fail(com.aura.springbook.common.exception.ResultCode.PARAM_ERROR, "新密码与旧密码相同");
        }
    }
    
    /**
     * 检查用户是否为管理员
     */
    @GetMapping("/{id}/admin")
    @Operation(summary = "检查用户是否为管理员", description = "根据用户ID检查是否为管理员")
    @Parameter(name = "id", description = "用户ID", required = true)
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功")
    })
    public R<Boolean> isAdmin(@PathVariable Long id) {
        logger.info("收到检查用户是否为管理员请求, 用户ID: {}", id);
        
        User user = userService.getUserById(id);
        if (user != null) {
            boolean isAdmin = user.isAdmin();
            logger.info("检查用户是否为管理员完成, 用户ID: {}, 结果: {}", id, isAdmin);
            return ResponseUtil.success(isAdmin);
        } else {
            logger.warn("检查用户是否为管理员失败, 用户ID: {} 不存在", id);
            return ResponseUtil.notFound();
        }
    }
    
    /**
     * 检查当前登录用户是否为管理员
     */
    @GetMapping("/current/admin")
    @Operation(summary = "检查当前用户是否为管理员", description = "检查当前登录用户是否为管理员")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功")
    })
    public R<Boolean> isCurrentAdmin(HttpServletRequest request) {
        logger.debug("收到检查当前用户是否为管理员请求");
        
        HttpSession session = request.getSession(false);
        if (session == null) {
            logger.debug("检查当前用户是否为管理员完成, 未登录, 结果: false");
            return ResponseUtil.success(false);
        }
        
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            logger.debug("检查当前用户是否为管理员完成, 未登录, 结果: false");
            return ResponseUtil.success(false);
        }
        
        User user = userService.getUserById(userId);
        boolean isAdmin = user != null && user.isAdmin();
        logger.debug("检查当前用户是否为管理员完成, 用户ID: {}, 结果: {}", userId, isAdmin);
        return ResponseUtil.success(isAdmin);
    }
}